package kr.hkit.androidcomplete03.ch281;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch281.common.Item;
import kr.hkit.androidcomplete03.ch281.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class JsonParser extends Activity {
	ListView list;
	ProgressDialog progressDlg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch281_parser);
		list = (ListView) findViewById(R.id.ch281_parser_listview);
		
		new ParseXml().execute("order.json");
	}
	
	private class ParseXml extends AsyncTask<String, Void, ArrayList<Item>>{
		@Override
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(JsonParser.this, "Wait", "order.xml & order.json Making. . . ");
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuffer sb =new StringBuffer();
			String str = null;
			BufferedReader fis;
			try {
				fis = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str = fis.readLine()) != null){
					sb.append(str);
				}
				fis.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return parsingXml(sb.toString());
		}
		
		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arItems = new ArrayList<Item>();
			Item itemClass;
			
			try {
				JSONArray ja = new JSONArray(xml);
				for(int i =0; i< ja.length(); i++){
					JSONObject order = ja.getJSONObject(i);
					itemClass = new Item();
					itemClass.setItemName(order.getString("Product"));
					itemClass.setItemPrice(order.getInt("Price"));
					itemClass.setItemMaker(order.getString("Maker"));
					arItems.add(itemClass);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return arItems;
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			MyAdapter adapter = new MyAdapter(JsonParser.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
		}
	}
}
